<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="体系名称" prop="dictName">
        <el-input
          v-model="queryParams.systemName"
          placeholder="请输入体系名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.time"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['system:system:query']" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:indicator:add']"
        >新增</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-if="deleteShow"-->
      <!--          v-hasPermi="['system:system:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="reset"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-row :flex="true" justify="space-between">
      <el-col :span="12">

        <el-table v-loading="loading" :data="sysList" @selection-change="handleSelectionChange" highlight-current-row>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号"  align="center" prop="id" />
          <el-table-column label="体系名称"  align="center" prop="systemName" :show-overflow-tooltip="false" />
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete2(scope.row)"
                v-hasPermi="['system:system:remove']"
                v-if="canDelete(scope.row)"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-search"
                @click="handleView(scope.row)"
                v-hasPermi="['system:tree:query']"
              >查看</el-button>
              <!--              <el-button-->
              <!--                size="mini"-->
              <!--                type="text"-->
              <!--                icon="el-icon-edit"-->
              <!--                @click="handleMatrix(scope.row), judgeDialogOpen=true"-->
              <!--                v-hasPermi="['system:tree:edit']"-->
              <!--              >专家评分</el-button>-->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleJudgeManage(scope.row)"
                v-if="canScore(scope.row)"
                v-hasPermi="['system:judgement:list']"
              >评分管理</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-col>
      <el-col :span="12" v-if="shouldRenderContent" class ="tree-view">
        <el-table v-loading="loading"
                  :data="dataList2"
                  @selection-change="handleSelectionChange"
                  row-key="id"
                  :default-expand-all="isExpandAll"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column type="selection" width="55" align="center" class ="tree-field"/>
          <el-table-column label="指标名称" align="center" prop="indicatorName" :show-overflow-tooltip="true" class ="tree-field"/>
          <el-table-column label="主观权重" align="center" prop="subjectiveWeight" :formatter="formatTwoDecimal"  :show-overflow-tooltip="true" class ="tree-field"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-search"
                @click="queryIndicator(scope.row)"
                v-hasPermi="['system:system:indicator']"
              >查看</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-col>
    </el-row>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="指标名称">
          {{ indicatorVo.indicatorName }}
        </el-descriptions-item>
        <el-descriptions-item label="指标描述">
          {{ indicatorVo.indicatorDescription }}
        </el-descriptions-item>
        <el-descriptions-item label="来源数据">
          {{ indicatorVo.dataSource }}
        </el-descriptions-item>
        <el-descriptions-item label="计算方式">
          {{ indicatorVo.calculationMethod }}
        </el-descriptions-item>
        <el-descriptions-item label="备注">
          {{ indicatorVo.description }}
        </el-descriptions-item>
        <el-descriptions-item label="主观权重">
          {{ indicatorVo.subjectiveWeight }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="hideDialog">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="专家打分"
      :visible.sync="judgeDialogOpen"
      width="80%"
      append-to-body
    >

      <el-descriptions>
        <el-descriptions-item label="评分准则">
          <ol>
            <li>点击下拉框可以选择两个指标的相对权重</li>
            <li>权重分为9、7、5、3、1、1/3、1/5、1/7、1/9一共九个等级，等级值依次减小</li>
            <li>权重等级值越大，表示上方指标的越重要，左方指标越不重要；权重等级值越小，表示上方指标越不重要，左方指标越重要</li>
          </ol>
        </el-descriptions-item>
      </el-descriptions>
      <el-row :gutter="20" style="min-height: 320px">

        <!--  左边表-->
        <el-col :span=10 >

          <el-tree
            :data="currentIndicatorSystem.children"
            :props="defaultProps"
            node-key="id"
            :expand-on-click-node="false"
            :highlight-current="true"
            default-expand-all
            ref="tree"
            style="overflow:scroll; max-height: 300px; min-height: 300px"
          >
  <span class="custom-tree-node" slot-scope="{ node, data }">
    <div class="flex-container">
      <span>{{ data.indicatorName }}</span>
      <el-button
        size="mini"
        type="text"
        icon="el-icon-search"
        v-show="data.children"
        @click="judgeIndicatorMatrix(data)"
      >打分</el-button>
    </div>
  </span>
          </el-tree>
        </el-col>
        <el-col :span="14" >
          <div class="custom-table">
            <table>
              <thead>
              <tr>
                <!-- 空白单元格 -->
                <th></th>
                <!-- 列标题 -->
                <th v-for="(col, index) in matrixData.colHeader" :key="index">{{ col }}</th>
              </tr>
              </thead>
              <tbody>
              <!-- 行数据 -->
              <tr v-for="(row, rowIndex) in matrixData.data" :key="rowIndex">
                <!-- 行标题 -->
                <td>{{ matrixData.rowHeader[rowIndex] }}</td>
                <!-- 单元格数据 -->
                <td v-for="(cell, cellIndex) in row" :key="cellIndex">
                  <!--                <el-input-number v-model:cell="matrixData.data[rowIndex][cellIndex]"> {{cell}}</el-input-number>-->
                  <el-select v-model="matrixData.data[rowIndex][cellIndex]" placeholder="请选择" style="max-width: 80px"
                             :disabled="rowIndex>=cellIndex"
                             @change="updateMatrixData(rowIndex,cellIndex)">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addIndicatorSysJudgement">提 交</el-button>
        <el-button @click="judgeDialogOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>

</script>
<script>
import { listMenu, getMenu, delMenu, addMenu, updateMenu} from "@/api/system/menu";
import { listJudgement, getJudgement, addJudgement, updateJudgement, delJudgement } from "@/api/indicator/judgement";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import {
  listSystem,
  getSystem,
  delSystem,
  addSystem,
  updateSystem,
  getSystemChildren,
  search,
  getIndicatorBySystemIdAndIndicatorId
} from "@/api/indicator/system";
import {getInfo} from "@/api/login";
import  {getIndicatorsBySystemId} from "@/api/indicator/indicator";
import { reactive } from 'vue';

export default {
  name: "system/index",
  dicts: ['sys_show_hide', 'sys_normal_disable'],
  components: { Treeselect, IconSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "查看指标信息",
      // 是否显示弹出层
      open: false,
      // 评分对话框显示状态，默认为false
      isScoreDialogOpen: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      //是否渲染右边表格，默认否
      shouldRenderContent:false,
      // 重新渲染表格状态
      refreshTable: true,
      // 评分对话框显示状态，默认为false
      judgeDialogOpen: false,
      // 评分管理对话框显示状态，默认为false
      manageJudgeDialogOpen: false,
      // 评分矩阵数据
      matrixData: {
        data:[],
        rowHeader: [],
        colHeader: []
      },
      curUserInfo:{},
      options: [
        { value: 9, label: "9" },
        { value: 7, label: "7" },
        { value: 5, label: "5" },
        { value: 3, label: "3" },
        { value: 1, label: "1" },
        { value: 0.33, label: "1/3" },
        { value: 0.2, label: "1/5" },
        { value: 0.14, label: "1/7" },
        { value: 0.11, label: "1/9" }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        systemName: null,
        description: null,
        createUser: null,
        modifyUser: null,
        modifyTime: null,
        time: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" }
        ]
      },
      //
      sysList: [],
      selectedRows: [],
      dataRange: {
        beginTime: "",
        endTime: ""
      },
      dataList2: [],
      total: 0,
      ids:[],
      currentSystemId: null,
      currentUserDeptId: undefined,  // 当前登录用户的部门信息
      indicatorVo: {
        indicatorName: null,
        dataSource: null,
        calculationMethod: null,
        description: null,
        subjectiveWeight: null,
        indicatorLevel: null
      },
      currentIndicatorSystem: {
        id: null,
        systemName: null,
        children: []
      },
    };
  },
  created() {
    this.getList();
    this.getCurrentUserDept();
  },
  methods: {
    formatTwoDecimal(row, column, cellValue) {
      return cellValue != null ? parseFloat(cellValue).toFixed(2) : '';
    },
    addIndicatorSysJudgement(){
      const temp ={
        indicatorSystemId: this.currentIndicatorSystem.id,
        judgeMatrix: JSON.stringify(this.currentIndicatorSystem),
        status: 0,
        userId: 0
      };
      addJudgement(temp).then(response=>{
        console.log(response);
        if(response.code === 200){
          this.$message.success("添加成功");
          this.judgeDialogOpen = false;
          this.reset();
        }else{
          this.$message.error("添加失败");
        }
      });
    },

    create2DArray(rows, columns) {
      const array2D = new Array(rows);

      for (let i = 0; i < rows; i++) {
        array2D[i] = new Array(columns).fill(1);
      }

      return array2D;
    },
    judgeIndicatorMatrix(data){
      if(data.judgementMatrix){
        console.log("test", data);
        this.matrixData = data.judgementMatrix;
        return;
      }
      data.judgementMatrix={
        rowHeader: [],
        colHeader: [],
        data: []
      };
      for(let i = 0; i < data.children.length; i++){
        console.log(data.children[i].indicatorName);
        data.judgementMatrix.rowHeader.push(data.children[i].indicatorName);
      }
      data.judgementMatrix.colHeader = data.judgementMatrix.rowHeader;
      data.judgementMatrix.data = this.create2DArray(data.children.length, data.children.length);
      this.matrixData = data.judgementMatrix;
      console.log('judge', data.judgementMatrix);
    },


    handleMatrix(row){
      console.log(row);
      this.loading = true;
      getIndicatorsBySystemId(row.id).then(response => {
        console.log(response);
        this.currentIndicatorSystem.systemName = row.systemName;
        this.currentIndicatorSystem.id = row.id;
        this.currentIndicatorSystem.children = [];
        this.currentIndicatorSystem.children.push({
          id: row.id,
          indicatorName: row.systemName,
          children: response.rows
        })
        this.loading = false;
      });
    },
    updateMatrixData(rowIndex,cellIndex){
      // 获取当前选中的值
      const currentValue = this.matrixData.data[rowIndex][cellIndex];
      // 计算对称位置的值
      let symmetricValue = 1.0 / currentValue;
      // 四舍五入保留两位小数
      if(symmetricValue > 1){
        symmetricValue = parseInt(symmetricValue.toFixed(0));
      }else{
        symmetricValue = parseFloat(symmetricValue.toFixed(2));
      }
      // 更新对称位置的值
      this.matrixData.data[cellIndex][rowIndex] = symmetricValue;
    },
    hideDialog(){
      this.open = false;
    },

    // 选择图标
    selected(name) {
      this.form.icon = name;
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    queryIndicator(row){
      if(this.currentSystemId!=null){
        getIndicatorBySystemIdAndIndicatorId(this.currentSystemId, row.id).then(response => {
          // console.log(response);
          this.indicatorVo = response.data;
          this.open = true;
          // console.log(this.indicatorVo);
        });
      }
    },
    /** 点击查看 */
    handleView(row){
      this.currentSystemId = row.id;
      // console.log(row);
      this.loading = true;
      getIndicatorsBySystemId(row.id).then(response => {

        console.log(response);
        this.menuOptions = [];
        const menu = { id: 0, indicatorName: '主类目', children: [] };
        this.currentIndicatorSystem.systemName = row.systemName;
        this.currentIndicatorSystem.id = row.id;
        this.currentIndicatorSystem.children = response.rows;
        //menu.children = this.handleTree(response.rows, "parentId");
        this.dataList2 = response.rows;
        this.shouldRenderContent = true;
        this.loading = false;
      });
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;

      listSystem(this.queryParams).then(response => {
        console.log(response);
        this.sysList = response.rows;
        this.loading = false;
      })
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      getIndicatorsBySystemId().then(response => {
        this.menuOptions = [];
        const menu = { menuId: 0, menuName: '主类目', children: [] };
        menu.children = this.handleTree(response.data, "menuId");
        this.menuOptions.push(menu);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        systemName: null,
        description: null,
        createUser: null,
        modifyUser: null,
        modifyTime: null,
        time: []
      }
      this.shouldRenderContent = false;
      this.currentIndicatorSystem = {
        id: null,
        systemName: null,
        children: []
      };
      this.matrixData = {
        data:[],
        rowHeader: [],
        colHeader: []
      };

      //this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      //this.getList();
      //console.log(this.queryParams);
      //this.dataList2 = [];

      if(this.queryParams.time == null){
        this.queryParams.time = ['', ''];
      }
      search(this.queryParams.systemName, this.queryParams.time[0], this.queryParams.time[1]).then(response => {
        this.loading=true;
        // console.log(response);
        this.sysList = response.rows;
        this.loading=false;
      });
      this.reset();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.$router.push('/access/system/newIndex');
    },
    handleJudgeManage(row){
      this.reset();
      this.$router.push({
        path: '/access/system/judgement',
        query: {
          id: row.id,
          name: row.systemName,
          content: row
        }
      });
    },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      // getMenu(row.id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改菜单";
      // });
    },
    /** 提交按钮 */
    // submitForm: function() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.menuId != undefined) {
    //         updateMenu(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addMenu(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    /** 删除按钮操作 */
    handleDelete() {
      const ids = this.selectedRows.map((item) => item.id);
      if (ids.length === 0) {
        this.$message({
          message: "请先选择要删除的数据",
          type: "warning",
        });
        return;
      }
      this.$modal
        .confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          delSystem(ids).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
            this.selectedRows = [];
          });
        });
    },

    handleDelete2(row) {
      this.ids.push(row.id);
      console.log(row.id);
      console.log(this.ids);
      console.log(this.ids.length);
      if (this.ids.length === 0) {
        this.$message({
          message: "请先选择要删除的指标",
          type: "warning",
        });
        return;
      }

      this.$modal
        .confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          delSystem(this.ids).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
            this.ids = [];
          });
        });
    },
    // 判断是否可以删除
    canDelete(row) {
      // 如果是管理员，或者创建部门与当前用户部门一致，则显示删除按钮
      return this.currentUserDeptId === 100 || row.createDeptId === this.currentUserDeptId;
    },
    // 获取当前用户部门信息
    getCurrentUserDept() {
      getInfo().then(res=>{
        this.curUserInfo = res.user;
        this.currentUserDeptId = this.curUserInfo.deptId;
        console.log(this.currentUserDeptId);
      });


      // 假设通过某种方式获取用户信息
      // return this.$store.state.userInfo.deptName;
    },
    // 判断是否可以进行评分管理
    canScore(row) {
      // 类似逻辑，评分管理权限判断
      console.log(this.currentUserDeptId);
      return this.currentUserDeptId === 100 ||this.currentUserDeptId === 110 || row.createDeptId === this.currentUserDeptId;
    },
  }
};
</script>

<style scoped>

::v-deep .el-table__body tr.current-row > td {
  background: rgb(197, 213, 255) !important;
}

::v-deep .el-table__column {
  white-space: normal !important;
}
::v-deep .tree-view .el-table .el-table__body .el-table__row :not(.el-table-column--selection){
  text-align: left; /* 左对齐文本 */
}

.custom-table table {
  width: 80%;
  border-collapse: collapse;
}

.custom-table th,
.custom-table td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: center;
}

.custom-table th {
  background-color: #f2f2f2;
}

.custom-table input[type="number"] {
  width: 100%;
  height: 100%;
  text-align: center;
}
</style>
